import yzBlank from "components/ui_components/yz_blank";
import groupListCell from "./components/groupListCell";
import { scrollMixin } from "../../../utils/mixin"; //引入加载更多

export default {
  mixins: [scrollMixin],
  data() {
    return {
      activeName: 0,
      dataList: [],
      titleArr: [],

      cardTotal: "---", //开团卡总数量
      isLoading: false,
      isLoadMore: true, //判断是否要加载更多的标志

      showActivePop: false, //点击去开团，展示拼团列表
      groupList: [],
      selectGroupId: null
    };
  },
  activated() {
    this.initOptions();
  },
  methods: {
    initOptions() {
      let GROUPlIST_URL = "plugin.ywm-fight-groups.frontend.controllers.fight-groups.get-member-join-teams"; //拼团列表，1-正在拼团，2-拼团成功，3-拼团失败
      let OPENCARD_URL = "plugin.ywm-fight-groups.frontend.controllers.fight-groups.my-open-group-card"; //我的开团卡
      this.dataList = [];
      this.titleArr = [
        {
          name: "正在拼团",
          url: GROUPlIST_URL,
          param: {
            team_status: 1
          }
        },
        {
          name: "拼团成功",
          url: GROUPlIST_URL,
          param: {
            team_status: 2
          }
        },
        {
          name: "拼团失败",
          url: GROUPlIST_URL,
          param: {
            team_status: 3
          }
        },
        {
          name: "我的开团卡",
          url: OPENCARD_URL,
          param: {},
          callback: data => {
            this.isLoadMore = true;
            this.cardTotal = data.card_number;
            this.dataList[this.activeName].isLoadMore = true;
            this.dataList[this.activeName].total_page = data.data.last_page;
            this.dataList[this.activeName].page = data.data.current_page;
            this.dataList[this.activeName].list = this.dataList[this.activeName].list.concat(data.data.data);
            // this.$set(this.dataList[this.activeName], "list", data.data.data);
            this.isLoading = false;
          }
        }
      ];

      this.activeName = this.$route.params.status || 0;
      this.$nextTick(() => {
        if (this.$refs.tabs) this.$refs.tabs.resize();
      });
      this.initData();
    },
    initData() {
      this.dataList = [];
      this.isLoadMore = true;
      this.titleArr.forEach((val, index) => {
        this.dataList.push({
          isLoadMore: true,
          page: 1,
          total_page: 0,
          list: []
        });
      });
      this.getData();
    },
    //下拉刷新
    loadTop() {
      console.log("触发下拉", this.activeName);
      this.initData();
      // this.getData(this.active);
      // this.$refs.loadmore.onTopLoaded();
    },
    cloneActivePop(){
      this.showActivePop = false;
    },
    getData() {
      if (this.dataList[this.activeName].list.length > 0) {
        return;
      }
      let json = {...this.titleArr[this.activeName].param};
      let _url = this.titleArr[this.activeName].url;

      $http.get(_url, json, "").then(
        response => {
          if (response.result === 1) {
            if (this.titleArr[this.activeName].callback) {
              return this.titleArr[this.activeName].callback(response.data);
            }
            this.isLoadMore = true;
            this.dataList[this.activeName].isLoadMore = true;
            this.dataList[this.activeName].total_page = response.data.last_page;
            this.dataList[this.activeName].page = 1;
            this.$set(this.dataList[this.activeName], "list", response.data.data);
            this.isLoading = false;
          } else {
            this.isLoading = false;
            this.$toast(response.msg);
          }
        },
        response => {}
      );
    },

    clickBtn(data) {
      // 按钮值：1-邀请好友,2-订单详情,3-拼团详情,4-去开团,5-使用开团卡开团
      const { value,tid, id, orderid } = data;
      let key = Number(value);
      switch (key) {
        case 1:
          this.shareWeixin(data);
          break;
        case 2:
          if (orderid) this.gotoUrl("orderdetail", { order_id: orderid, orderType: "ywmgroups" });
          break;
        case 3:
          this.gotoUrl("GroupDetail", { id: tid }, { plu: "ywm" });
          break;
        case 4:
          this.selectGroupId = id;
          this.getActiveList();
          break;
        case 5:
          this.gotoUrl("ywmGroupList", { id: id }, {});
          break;
        default:
          break;
      }
    },
    getActiveList() {
      $http
        .get("plugin.ywm-fight-groups.frontend.controllers.fight-groups.index", {}, "加载中")
        .then(res => {
          if (res.result == 1) {
            this.groupList = res.data.data;
            this.showActivePop = true;
          } else {
            this.$toast(res.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    openTeam(e) {
      this.$dialog
        .confirm({
          title: "提示",
          message: `是否确认选中【${e.title}】开团`
        })
        .then(() => {
          this.openTeamQuest(e);
        });
    },
    openTeamQuest(e) {
      $http
        .get("plugin.ywm-fight-groups.frontend.controllers.fight-groups.auto-open-group", { team_member_id: this.selectGroupId, group_id: e.id }, "加载中")
        .then(res => {
          this.$toast(res.msg);
          if (res.result == 1) {
            this.showActivePop = false;
            this.initData();
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    gotoUrl(name, params = {}, query = {}) {
      this.$router.push(this.fun.getUrl(name, params, query));
    },

    gotoGroup(obj) {
      let json = { id: obj.team_id };
      if (obj.store_id) {
        json.store_id = obj.store_id;
      }
      this.$router.push(this.fun.getUrl("GroupDetail", json));
    },
    //获取更多数据，加载更多
    getMoreData() {
      this.isLoadMore = false; // 防止多次请求分页数据
      let json = {...this.titleArr[this.activeName].param};
      let _url = this.titleArr[this.activeName].url;

      const { page, total_page } = this.dataList[this.activeName];
      if (page >= total_page) {
        return;
      } else {
        let lastpage = page + 1;
        json.page = lastpage;

        $http
          .get(_url, json, "加载中")
          .then(res => {
            this.isLoadMore = true;
            if (res.result == 1) {
              let nextPageData = res.data.data;
              if (this.titleArr[this.activeName].callback) {
                return this.titleArr[this.activeName].callback(res.data);
              }
              this.dataList[this.activeName].page = lastpage;
              this.dataList[this.activeName].list = this.dataList[this.activeName].list.concat(nextPageData); //数组拼接
            } else {
              this.isLoadMore = false;
              this.dataList[this.activeName].isLoadMore = false;
            }
          })
          .catch(error => {
            console.log(error);
          });
      }
    },
    //分享
    shareWeixin(e) {
      const { tid, good } = e;
      let uid = window.localStorage.getItem("uid");
      let _title = good.title;
      let _imgUrl = good.thumb;
      let _desc = "分享拼团活动";
      let _link = `${this.fun.getSiteRoot()}/addons/yun_shop/?menu#/group_detail/${tid}?i=${this.fun.getKeyByI()}&mid=${uid}&plu=ywm`;
      let json = {
        title: _title, // 分享标题
        desc: _desc, // 分享描述
        link: _link, // 分享链接
        imgUrl: _imgUrl // 分享图标
      };

      if (this.fun.getTyep() == 7 || this.fun.isCPS()) {
        this.appShare(json);
        return;
      } else if (this.fun.getTyep() == 5) {
        //不是微信端 不访问
        return;
      }
      this.fun.wxShare(
        "",
        {},
        {
          title: json.title,
          imgUrl: json.imgUrl,
          description: json.desc,
          link: json.link
        }
      );
      this.$dialog.alert({ message: "请点击右上角微信分享" });
    },
    //app分享设置
    appShare(json) {
      if (this.fun.isCPS()) {
        if (this.fun.isIosOrAndroid() === "ios") {
          shareByH5IOS({ body: "shareByH5IOS", json: JSON.stringify(json) });
        } else {
          console.log(JSON.stringify(json));
          shareByH5Android(JSON.stringify(json));
        }
      } else {
        YDB.Share(json.title, json.desc, json.imgUrl, json.link, "Sharesback");
      }
    }
  },
  components: { yzBlank, groupListCell },
  filters: {
    startTimes(t) {
      // let unixTimestamp = new Date(t * 1000);
      // return unixTimestamp.toLocaleString();
      let date = new Date(t * 1000);
      let Y = date.getFullYear() + "-";
      let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
      let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      let h = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      let m = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
      let s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    }
  }
};
